package com.laxcen.smoke.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.laxcen.model.User;
import com.laxcen.smoke.config.CommonEnum;
import com.laxcen.smoke.dao.UserDao;
import com.laxcen.smoke.dto.res.UserMessageRes;
import com.laxcen.smoke.dto.res.UserResourceRes;
import com.laxcen.smoke.service.UsersService;
import com.laxcen.smoke.util.DBUtils;
import com.laxcen.smoke.util.Response;
import com.laxcen.util.PasswordHelper;
import com.laxcen.util.ResultUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Service
public class UsersServiceImpl implements UsersService {

    @Autowired
    private UserDao userDao;

    @Override
    public Response insert(String username, String account, String password, int roleflag, int onoroff,String province,String city,String area) throws Exception {
        List<String> list = userDao.getAccountAll();
        if (list.contains(account)){
            return new Response(CommonEnum.ACCOUNT_EXIST);
        }
        List<String> llist = userDao.getUsernameAll();
        if (llist.contains(username)){
            return new Response(CommonEnum.USERNAME_EXIST);
        }
        if (password==null||"".equals(password)){
            return new Response(CommonEnum.PASSWORD_IS_NULL);
        }
        if (roleflag==0) {
            long ids = DBUtils.nextId();
            String id = String.valueOf(ids);
            String salt = PasswordHelper.getSalt();
            String newpassword = PasswordHelper.encryptPassword(username,password,salt);
            userDao.insert(id, username, account, newpassword, salt,roleflag, onoroff,null,null,null, new Date());
        }else if (roleflag==1){
            long ids = DBUtils.nextId();
            String id = String.valueOf(ids);
            String salt = PasswordHelper.getSalt();
            String newpassword = PasswordHelper.encryptPassword(username,password,salt);
            userDao.insert(id, username, account, newpassword, salt,roleflag, onoroff,province,city,area, new Date());
        }
        Response response = new Response();
        response.setOK();
        return response;
    }

    @Override
    public Response update(String id,String username, String account, String password, int roleflag, int onoroff,String province,String city,String area) throws Exception {
        List<String> list = userDao.getAccountByOne(id);
        if (list.contains(account)){
            return new Response(CommonEnum.ACCOUNT_EXIST);
        }
        List<String> llist = userDao.getUsernameByOne(id);
        if (llist.contains(username)){
            return new Response(CommonEnum.USERNAME_EXIST);
        }
        if (password==null||"".equals(password)){
             password = userDao.getPassByAccoAll(account);
        }
        if (roleflag==0) {
            String salt = PasswordHelper.getSalt();
            String newpassword = PasswordHelper.encryptPassword(username,password,salt);
            userDao.update(id,username,account, newpassword,salt,roleflag,onoroff,null,null,null,new Date());
        }else if (roleflag==1){
            String salt = PasswordHelper.getSalt();
            String newpassword = PasswordHelper.encryptPassword(username,password,salt);
            userDao.update(id,username,account,newpassword,salt,roleflag,onoroff,province,city,area,new Date());
        }
        Response response = new Response();
        response.setOK();
        return response;
    }

    @Override
    public Response delete(String id) {
        userDao.delete(id);
        userDao.deleteUserAndRole(id);
        Response response = new Response();
        response.setOK();
        return response;
    }

    @Override
    public Response deletemore(String id) {
        String[] ids = id.split(",");
        for (int i = 0;i < ids.length;i++){
            userDao.delete(ids[i]);
            userDao.deleteUserAndRole(ids[i]);
        }
        Response response = new Response();
        response.setOK();
        return response;
    }

    @Override
    public Response<PageInfo<UserMessageRes>> getAllUser(int pageNo, int pageSize) {
        Page page = PageHelper.startPage(pageNo, pageSize);
        List<UserMessageRes> list = userDao.getUserList();
        Response<PageInfo<UserMessageRes>> response = new Response<>();
        PageInfo pageInfo = page.toPageInfo();
        pageInfo.setList(list);
        response.setOK();
        response.setData(pageInfo);
        return response;
    }

    @Override
    public Response<PageInfo<UserMessageRes>> getDefineList(String account, String username, int pageNo, int pageSize) throws ParseException {
        Page page = PageHelper.startPage(pageNo, pageSize);
        List<UserMessageRes> list = new LinkedList<>();
//        if ("".equals(account)&&"".equals(starttime)&&"".equals(endtime)){
//            list = userDao.getUserList();
//        }else
            if ("".equals(account)&&"".equals(username)){
//            if (account==null&&starttime==null&&endtime==null){
            list = userDao.getUserList();
        }
//            else if ("".equals(account)&&!"".equals(starttime)&&!"".equals(endtime)){
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd") ;
//            Date datestart = sdf.parse(starttime);
//            Date dateend = sdf.parse(endtime);
//            list = userDao.getListByTime(datestart,dateend);
//        }
//        else if (!"".equals(account)&&"".equals(starttime)&&"".equals(endtime)){
        else if (!"".equals(account)&&"".equals(username)){
            list = userDao.getListByAccount(account);
        }else if ("".equals(account)&&!"".equals(username)){
                list = userDao.getListByUSername(username);
            }else if (null==account&&null==username){
                list = userDao.getUserList();
            }else if (!"".equals(account)&&!"".equals(username)){
                list = userDao.getListByUSernameAndAccount(account,username);
            }else if (null!=account&&null==username){
                list = userDao.getListByAccount(account);
            }else if (null==account&&null!=username){
                list = userDao.getListByUSername(username);
            }else if (null!=account&&null!=username){
                list = userDao.getListByUSernameAndAccount(account,username);
            }
//        else if (!"".equals(account)&&!"".equals(starttime)&&!"".equals(endtime)){
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd") ;
//            Date datestart = sdf.parse(starttime);
//            Date dateend = sdf.parse(endtime);
//            list = userDao.getListByTimeAndAcc(account,datestart,dateend);
//        }else if (account==null&&starttime!=null&&endtime!=null){
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd") ;
//            Date datestart = sdf.parse(starttime);
//            Date dateend = sdf.parse(endtime);
//            list = userDao.getListByTime(datestart,dateend);
//        }else if (account!=null&&starttime==null&&endtime==null){
//            list = userDao.getListByAccount(account);
//        }else if (account!=null&&starttime!=null&&endtime!=null){
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd") ;
//            Date datestart = sdf.parse(starttime);
//            Date dateend = sdf.parse(endtime);
//            list = userDao.getListByTimeAndAcc(account,datestart,dateend);
//        }
       Response<PageInfo<UserMessageRes>> response = new Response<>();
        PageInfo pageInfo = page.toPageInfo();
        pageInfo.setList(list);
        response.setOK();
        response.setData(pageInfo);
        return response;
    }

    @Override
    public Response<UserMessageRes> sign(String account, String password, HttpServletRequest hsrequest, HttpServletResponse hresponse) {
        List<String> realaccount = userDao.getAccountOn(0);
        Response response = new Response();
        if (!realaccount.contains(account)){
            return new Response<>(CommonEnum.ACCOUNT_NOT_EXIST);
        }

        UserMessageRes userMessageRes = userDao.getUserOne(account);
        System.out.println(JSON.toJSON(userMessageRes));
        UsernamePasswordToken token = new UsernamePasswordToken(userMessageRes.getUsername(), password);
        try{
            token.setRememberMe(false);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            userMessageRes.setCookie(hsrequest.getSession().getId());
            response.setError(200);
            response.setMsg("登录成功");
            response.setData(userMessageRes);
        } catch (LockedAccountException e) {
            token.clear();
            return  new Response<>(CommonEnum.PASSWORD_LOCK);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            token.clear();
            return  new Response<>(CommonEnum.PASSWORD_WRONG);
        }
        return response;
    }

    @Override
    public UserMessageRes getOne(String account) {
        return userDao.getUserOne(account);
    }

    @Override
    public Response distribute(String userid, long roleid) {
        userDao.insertUserRole(userid,roleid,new Date());
        Response response = new Response();
        response.setOK();
        return response;
    }

    @Override
    public Response<List<UserResourceRes>> getUserResource(String userid) {
        List<UserResourceRes> list = userDao.getUserResource(userid);
        Response<List<UserResourceRes>> response = new Response<>();
        response.setOK();
        response.setData(list);
        return response;
    }
}
